package com.nsgf.library.utils;


import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.nsgf.library.R;


/**
 * 统一Toast的入口,Toast变成单例,方便UI定制
 *
 * @author Desmond
 * @version [version, 2015-8-8]
 */
public class CustomToast {

    private static Toast mToast;
    private static Handler mHandler;
    private static Runnable r = new Runnable() {
        public void run() {
            if (null == mToast)
                return;
            mToast.cancel();
            mToast = null;//toast隐藏后，将其置为null
        }
    };


    public synchronized static void showToast(Context context, final String text) {
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        if (StringUtil.isEmpty(text))
            return;
        mHandler.removeCallbacks(r);
        if (mToast == null && context != null && !StringUtil.isEmpty(text)) {//只有mToast==null时才重新创建，否则只需更改提示文字
            View rootView = View.inflate(context, R.layout.custom_toast, null);
            TextView contentText = (TextView) rootView.findViewById(R.id.content_text);
            contentText.setText(text);

            mToast = new Toast(context);
            mToast.setGravity(Gravity.CENTER, 0, 0);
            mToast.setView(rootView);
            mToast.setDuration(Toast.LENGTH_SHORT);
        } else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (!StringUtil.isEmpty(text)) {
                        ((TextView) mToast.getView().findViewById(R.id.content_text)).setText(text);
                    }
                }
            });
        }
        mHandler.postDelayed(r, 2000);//延迟LENGTH_SHORT秒隐藏toast  分别对应Toast.LENGTH_LONG（3.5秒）和Toast.LENGTH_SHORT（2秒）的值
        mToast.show();
    }
}
